package com.zjl.filter;

import com.alibaba.fastjson.JSON;
import com.zjl.pojo.Result;
import com.zjl.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        log.info("拦截请求：{}", req.getRequestURI());
        String requestURI = req.getRequestURI();
        String[] urls = new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "user/loginout"
        };
        boolean check = check(urls, requestURI);
        if(check) {
            log.info("路径不需要处理！");
            chain.doFilter(req, res);
            return;
        }
        // 查看管理员是否登录
        if(req.getSession().getAttribute("employee") != null) {
            log.info("员工已登录,用户id为：{}", req.getSession().getId());

            Long employeeId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

            chain.doFilter(req, res);
            return;
        }

        // 检查员工是否登陆
        if(req.getSession().getAttribute("user") != null) {
            log.info("用户已登录,用户id为：{}", req.getSession().getId());
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            chain.doFilter(req, res);
            return;
        }

        res.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    // 路径匹配
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match) {
                return true;
            }
        }
        return false;
    }
}
